package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
public class SetmealServiceImpl implements SetmealService {

    private static final Logger log = LoggerFactory.getLogger(SetmealServiceImpl.class);
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishMapper dishMapper;
    /**
     * 新增套餐
     * @param setmealDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        // 1. 向套餐表插入数据
        setmealMapper.insert(setmeal);

        // 2. 向套餐菜品关系表插入数据
        // 2.1 获取套餐id
        Long id = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if(!setmealDishes.isEmpty()){
            setmealDishes.forEach(item -> {
                item.setSetmealId(id);
            });
        }
        // 2.2 批量插入套餐菜品关系数据
        setmealDishMapper.insertBatch(setmealDishes);
    }

    /**
     * 套餐分页查询
     * @param setmealPageQueryDTO 前端返回的数据
     * @return
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        // 开始分页查询
        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);
        // 获取分页结果
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除套餐
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Long> ids) {
        // 1.起售中的套餐不能删除
        List<SetmealVO> setmealVOS = setmealMapper.selectById(ids);
        if(!setmealVOS.isEmpty()){
            setmealVOS.forEach(item -> {
                if(Objects.equals(item.getStatus(), StatusConstant.ENABLE)){
                    throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
                }
            });
        }

        // 2.删除套餐数据
        setmealMapper.deleteBatch(ids);
        setmealDishMapper.deleteBySetmealId(ids);
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SetmealVO getById(Long id) {
        // 1.查询套餐数据
        SetmealVO setmealVO = setmealMapper.getById(id);
        // 2.查询套餐关联的菜品数据
        List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(id);
        // 3.将关联的数据存入套餐对象中
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    /**
     * 修改套餐
     * @param setmealDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SetmealDTO setmealDTO) {
        // 1.修改套餐表数据
        setmealMapper.update(setmealDTO);

        // 2.修改套餐菜品关系表数据
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if(!setmealDishes.isEmpty()){
            // 2.1 删除套餐菜品关系表中原始数据
            List<Long> ids = new ArrayList<>();
            ids.add(setmealDTO.getId());
            setmealDishMapper.deleteBySetmealId(ids);

            // 2.2 插入套餐菜品关系表数据
            setmealDishes.forEach(item -> {
                item.setSetmealId(setmealDTO.getId());
            });
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startOrStop(Integer status, Long id) {
        // 起售套餐时，如果套餐内包含停售的菜品，则不能起售
        if(status.equals(StatusConstant.ENABLE)){
            // 查询菜品的所有信息
            List<Dish> dishList = dishMapper.selectDishInfoByIdBatch(Collections.singletonList(id));
            for(Dish item : dishList){
                if(item.getStatus().equals(StatusConstant.DISABLE)){
                    throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
            }
        }
        SetmealDTO setmealDTO = new SetmealDTO();
        setmealDTO.setId(id);
        setmealDTO.setStatus(status);
        setmealMapper.update(setmealDTO);
    }

    /**
     * 根据分类id查询套餐
     * @param categoryId
     * @return
     */
    @Override
    public List<Setmeal> selectSetmealBeyCategoryId(Long categoryId) {
        Setmeal setmeal = Setmeal.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Setmeal> setmealList = setmealMapper.selectByCategoryId(setmeal);
        return setmealList;
    }

    /**
     * 根据套餐id查询菜品
     * @param id
     * @return
     */
    @Override
    public List<DishItemVO> getSetmealWithDish(Long id) {
        List<DishItemVO> dishItemVOList = dishMapper.getSetmealWithDish(id);
        return dishItemVOList;
    }

}
